package org.jetlinks.pro.things.impl.connector;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.bean.FastBeanCopier;
import org.jetlinks.core.event.EventBus;
import org.jetlinks.pro.things.ThingsConnector;
import org.jetlinks.pro.things.ThingsConnectorManager;
import org.jetlinks.pro.things.ThingsConnectorProvider;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Set;

@AllArgsConstructor
@Component
public class ThingPropertiesMessageConnectorProvider implements ThingsConnectorProvider {

    private final EventBus eventBus;

    private final ThingsConnectorManager connectorManager;


    @Override
    public String getId() {
        return "thing-property";
    }

    @Override
    public String getName() {
        return "物属性";
    }

    @Override
    public Mono<ThingsConnector> createConnector(Map<String, Object> configuration) {
        PropertyConnectorProperties properties = FastBeanCopier.copy(configuration, new PropertyConnectorProperties());
        properties.validate();
        return Mono
            .just(
                new ThingPropertiesMessageConnector(properties.thingType,
                                                    properties.templateId,
                                                    properties.thingId,
                                                    eventBus,
                                                    properties.properties,
                                                    connectorManager
                )
            );
    }

    @Getter
    @Setter
    public static class PropertyConnectorProperties {
        private String thingType;
        private String templateId;
        private String thingId;
        private Set<String> properties;

        public void validate() {
            Assert.hasText(thingType, "thingType can not be empty");
            Assert.hasText(templateId, "templateId can not be empty");
            Assert.notEmpty(properties, "properties can not be empty");
        }
    }
}
